<template>
  <div class="container">
    <h1>Request Overview</h1>
    
    <!-- 搜索框 -->
    <div class="search-container">
      <input v-model="searchReqId" @input="fetchRequests" placeholder="搜索 Req_id" />
      <input v-model="searchItem" @input="fetchRequests" placeholder="搜索 Item" />
      <input v-model="searchPriority" @input="fetchRequests" placeholder="搜索 Priority" />
      <input v-model="currentUserNickname" placeholder="搜索 Opened By" disabled /> <!-- 禁用并显示当前用户昵称 -->
      <input v-model="searchState" @input="fetchRequests" placeholder="搜索 State" />
      <input v-model="searchShortDescription" @input="fetchRequests" placeholder="搜索 Short Description" />
      <input v-model="searchAssignedTo" @input="fetchRequests" placeholder="搜索 Assigned To" />
      <input v-model="searchAssignmentGroup" @input="fetchRequests" placeholder="搜索 Assignment Group" />
      <input v-model="searchProject" @input="fetchRequests" placeholder="搜索 Project" />
      <button @click="showConfirmationDialog" :disabled="selectedRequests.length === 0">删除</button> <!-- 删除按钮 -->
    </div>
    
    <!-- 表格 -->
    <table>
      <thead>
        <tr>
          <th>Select</th> <!-- 新增复选框列 -->
          <th>Req_id</th>
          <th>Opened</th>
          <th>Opened By</th>
          <th>State</th>
          <th>Item</th>
          <th>Priority</th>
          <th>Short Description</th>
          <th>Description</th>
          <th>Assigned To</th>
          <th>Assignment Group</th>
          <th>Project</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="request in requests" :key="request.id">
          <td>
            <input type="checkbox" :value="request.Req_id" v-model="selectedRequests" /> <!-- 复选框绑定到 selectedRequests -->
          </td>
          <td @click="goToDetail(request.Req_id)" class="clickable">{{ request.Req_id }}</td>
          <td>{{ formatDate(request.Opened) }}</td>
          <td>{{ request.Opened_by }}</td>
          <td>{{ request.State }}</td>
          <td>
            <span @click="toggleFullDescription(request.id, 'item')" class="description-text">
              {{ request.Item.substring(0, 15) }}<span v-if="fullDescriptionId === request.id && fullDescriptionType === 'item'">...{{ request.Item }}</span>
            </span>
          </td>
          <td>{{ request.Priority }}</td>
          <td>
            <span @click="toggleFullDescription(request.id, 'shortDescription')" class="description-text">
              {{ request.Short_description.substring(0, 10) }}<span v-if="fullDescriptionId === request.id && fullDescriptionType === 'shortDescription'">...{{ request.Short_description }}</span>
            </span>
          </td>
          <td>
            <span @click="toggleFullDescription(request.id, 'description')" class="description-text">
              {{ request.Description.substring(0, 10) }}<span v-if="fullDescriptionId === request.id && fullDescriptionType === 'description'">...{{ request.Description }}</span>
            </span>
          </td>
          <td>{{ request.Assigned_to }}</td>
          <td>{{ request.Assignment_group }}</td>
          <td>{{ request.Project }}</td>
        </tr>
      </tbody>
    </table>
    
    <!-- 分页 -->
    <div class="pagination">
      <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>第 {{ currentPage }} 页，共 {{ total }} 条</span>
      <button @click="nextPage" :disabled="currentPage * limit >= total">下一页</button>
    </div>
    
    <!-- 删除确认对话框 -->
    <ConfirmationDialog v-if="isConfirmationDialogVisible" @confirm="deleteSelectedRequests" @cancel="hideConfirmationDialog" />
  </div>
</template>



<script>
import axios from 'axios';
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import ConfirmationDialog from '../components/ConfirmationDialog.vue'; // 引入确认对话框组件

export default {
  components: {
    ConfirmationDialog
  },
  setup() {
    const requests = ref([]);
    const selectedRequests = ref([]);
    const total = ref(0);
    const currentPage = ref(1);
    const limit = ref(10);
    const searchReqId = ref('');
    const searchItem = ref('');
    const searchPriority = ref('');
    const currentUserNickname = ref('');
    const searchState = ref('');
    const searchShortDescription = ref('');
    const searchAssignedTo = ref('');
    const searchAssignmentGroup = ref('');
    const searchProject = ref('');
    const router = useRouter();
    const fullDescriptionId = ref(null);
    const fullDescriptionType = ref(null);
    const isConfirmationDialogVisible = ref(false); // 控制确认对话框的显示

    // 显示确认对话框
    const showConfirmationDialog = () => {
      if (selectedRequests.value.length === 0) {
        alert("请选择要删除的项");
      } else {
        isConfirmationDialogVisible.value = true;
      }
    };

    // 隐藏确认对话框
    const hideConfirmationDialog = () => {
      isConfirmationDialogVisible.value = false;
    };

    // 删除选中的请求
    const deleteSelectedRequests = async () => {
      try {
        await axios.post('http://localhost:3000/api/requests', {
          ids: selectedRequests.value
        });
        requests.value = requests.value.filter(request => !selectedRequests.value.includes(request.Req_id));
        selectedRequests.value = [];
        alert("Request删除成功");
        hideConfirmationDialog(); // 关闭对话框
      } catch (error) {
        console.error("删除失败:", error);
        alert("删除失败：" + error.message);
      }
    };

    // 获取当前用户的昵称
    onMounted(async () => {
      const username = localStorage.getItem('username');
      const userRole = localStorage.getItem('userRole');
      if (username && userRole) {
        try {
          const response = await axios.post('http://localhost:3000/api/getNickname', { username, userRole });
          currentUserNickname.value = response.data.nickname;
          if (currentUserNickname.value) {
            fetchRequests();
          }
        } catch (error) {
          console.error('获取用户昵称失败:', error);
        }
      }
    });

    const fetchRequests = async () => {
      try {
        const response = await axios.get('http://localhost:3000/api/requests', {
          params: {
            page: currentPage.value,
            limit: limit.value,
            searchReqId: searchReqId.value,
            searchItem: searchItem.value,
            searchPriority: searchPriority.value,
            searchOpenedBy: currentUserNickname.value,
            searchState: searchState.value,
            searchShortDescription: searchShortDescription.value,
            searchAssignedTo: searchAssignedTo.value,
            searchAssignmentGroup: searchAssignmentGroup.value,
            searchProject: searchProject.value
          }
        });
        requests.value = response.data.requests;
        total.value = response.data.total;
      } catch (error) {
        console.error('获取数据失败:', error);
        alert('获取数据失败: ' + error.message);
      }
    };

    const nextPage = () => {
      if (currentPage.value * limit.value < total.value) {
        currentPage.value++;
        fetchRequests();
      }
    };

    const prevPage = () => {
      if (currentPage.value > 1) {
        currentPage.value--;
        fetchRequests();
      }
    };

    const goToDetail = (reqId) => {
      router.push({ name: 'RequestDetailforObyMe', params: { reqId } });
    };

    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString();
    };

    const toggleFullDescription = (id, type) => {
      fullDescriptionId.value = fullDescriptionId.value === id && fullDescriptionType.value === type ? null : id;
      fullDescriptionType.value = type;
    };

    return {
      requests,
      total,
      currentPage,
      limit,
      searchReqId,
      searchItem,
      searchPriority,
      currentUserNickname,
      searchState,
      searchShortDescription,
      searchAssignedTo,
      searchAssignmentGroup,
      searchProject,
      selectedRequests,
      fetchRequests,
      deleteSelectedRequests,
      nextPage,
      prevPage,
      goToDetail,
      formatDate,
      toggleFullDescription,
      fullDescriptionId,
      fullDescriptionType,
      isConfirmationDialogVisible,
      showConfirmationDialog,
      hideConfirmationDialog
    };
  }
};
</script>

<style scoped>
.container {
  max-width: 1500px;
  padding: 10px;
  margin-bottom: 150px;
  background-color: white; /* 白色背景 */
  border-radius: 10px; /* 圆角 */
  padding: 20px; /* 内边距 */
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 添加阴影 */
}

h1 {
  margin-top: 10px;
  margin-bottom: 10px;
}

.search-container {
  margin-bottom: 20px;
}

.search-container input {
  margin-right: 10px;
  width: 110px;
  border-radius: 4px; /* 圆角 */
  border: 1px solid #ccc; /* 边框颜色 */
  padding: 8px; /* 内边距 */
  transition: border-color 0.3s; /* 边框颜色过渡效果 */
}

.search-container input:hover {
  border-color: #007bff; /* 悬停时边框颜色 */
}

.search-container button {
  background-color: red; /* 红色背景 */
  color: white; /* 白色文字 */
  border: none;
  border-radius: 4px; /* 圆角 */
  padding: 8px 16px; /* 内边距 */
  margin-left: 10px; /* 与搜索框的间距 */
  cursor: pointer;
  transition: background-color 0.3s; /* 颜色过渡效果 */
}

.search-container button:hover {
  background-color: #410303; /* 悬停时深蓝色背景 */
}

.search-container button:disabled {
  background-color: #ccc; /* 禁用状态的灰色背景 */
  cursor: not-allowed;
}

table {
  width: 100%;
  border-collapse: collapse;
  font-size: 13px;
}

table th, table td {
  border: 1px solid #ddd;
  padding: 4px;
}

.clickable {
  color: blue;
  cursor: pointer;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

.pagination button {
  background-color: #007bff; /* 蓝色背景 */
  color: white; /* 白色文字 */
  border: none;
  border-radius: 4px; /* 圆角 */
  padding: 8px 16px; /* 内边距 */
  margin: 0 10px; /* 按钮间距 */
  cursor: pointer;
  transition: background-color 0.3s; /* 颜色过渡效果 */
}

.pagination button:hover {
  background-color: #0056b3; /* 悬停时深蓝色背景 */
}

.pagination button:disabled {
  background-color: #ccc; /* 禁用状态的灰色背景 */
  cursor: not-allowed;
}
</style>